#-*- coding:utf-8 -*-
import csv
import os
import sys
from PySide2.QtCore import *
from PySide2.QtGui import *
from PySide2.QtWidgets import *
from Windows.MainWindow import MainWindow
from Windows.setup_window import Setup
from Widgets.palette_color import showColor
from Windows.ProjectInfoWindow import ProjectInfoWindow

class Login(QWidget):
    '''
    打开时，先从服务器中的project_db中下载到本地projects当中，管理者有权限直接删除软件，非管理者不能直接删除
    '''
    def __init__(self):
        super(Login,self).__init__()

        self.setPalette(showColor('bg'))
        self.CONFIG_PATH=os.path.join(os.path.dirname(__file__),'config')
        self.USER_INFO_PATH=os.path.join(self.CONFIG_PATH,'user.info')
        self.IMG_PATH=os.path.join(os.path.dirname(__file__),'imgs')
        self.PYTHON_PATH='C:/Python3_7_2/python3.exe'
        # self.SNIPASTE_PATH=os.path.dirname(__file__)+'/Plugins/Snipaste/Snipaste.exe'

        self.setWindowTitle('BrickMover')
        icon = QIcon()
        icon_path = os.path.join(self.IMG_PATH , 'zt.png')
        icon.addPixmap(QPixmap(icon_path))
        self.setWindowIcon(icon)
        self.mainLayout=QHBoxLayout()

        self.left_img=QLabel()
        self.left_img.setPixmap(QPixmap(os.path.dirname(__file__)+"/config/bricker.jpg"))

        self.login_layout=QVBoxLayout()


        self.logo_layout=QHBoxLayout()
        self.logo_layout.setAlignment(Qt.AlignCenter)
        self.logo_layout.setContentsMargins(20,25,10,5)
        self.logo_label=QLabel('欢迎使用搬砖工')
        self.logo_label.setFont(QFont('',15,75))
        self.logo_label.setPalette(showColor('font'))


        self.logo_layout.addWidget(self.logo_label)

        self.user_layout=QHBoxLayout()
        self.user_layout.setAlignment(Qt.AlignCenter)
        self.user_layout.setContentsMargins(10,25,10,5)
        self.username_label=QLabel('用户名： ')
        self.username_label.setPalette(showColor('font'))
        self.username_eidt=QLineEdit()
        self.user_layout.addWidget(self.username_label)
        self.user_layout.addWidget(self.username_eidt)

        self.password_layout=QHBoxLayout()
        self.password_layout.setAlignment(Qt.AlignCenter)
        self.password_layout.setContentsMargins(10,5,10,15)
        self.password_label=QLabel('密  码:  ')
        self.password_label.setPalette(showColor('font'))
        self.password_edit=QLineEdit()
        self.password_edit.setEchoMode(QLineEdit.Password)
        self.password_layout.addWidget(self.password_label)
        self.password_layout.addWidget(self.password_edit)

        self.btn_layout=QHBoxLayout()
        self.btn_layout.setContentsMargins(10, 5, 10, 15)
        self.login_btn=QPushButton('登录')
        self.login_btn.setPalette(showColor('bg'))
        # self.login_btn.setShortcut(QKeySequence('Enter'))
        self.login_btn.setShortcut(Qt.Key_Return|Qt.Key_Enter)
        self.login_btn.clicked.connect(self.user_login)

        # self.setup_btn=QPushButton('注册')
        # self.setup_btn.clicked.connect(self.user_setup)
        # self.btn_layout.addWidget(self.setup_btn)

        self.setting_btn=QPushButton('设置')
        self.setting_btn.clicked.connect(self.setting)
        self.btn_layout.addWidget(self.login_btn)
        self.btn_layout.addWidget(self.setting_btn)

        self.custom_config_layout=QHBoxLayout()
        # self.custom_config_layout.setAlignment(Qt.AlignCenter)
        self.custom_config_layout.setContentsMargins(10, 5, 10, 10)
        self.custom_config_layout.setSpacing(80)
        check_font = QFont('', 8)
        self.auto_check=QCheckBox('自动登录')
        self.auto_check.setFont(check_font)
        self.auto_check.setPalette(showColor('font'))
        self.auto_check.stateChanged.connect(self._check_change)
        self.save_password_check=QCheckBox('记住密码')
        self.save_password_check.setFont(check_font)
        self.save_password_check.stateChanged.connect(self._check_change)
        self.save_password_check.setPalette(showColor('font'))
        self.custom_config_layout.addWidget(self.auto_check)
        self.custom_config_layout.addWidget(self.save_password_check)

        self.login_layout.addLayout(self.logo_layout)
        self.login_layout.addLayout(self.user_layout)
        self.login_layout.addLayout(self.password_layout)
        self.login_layout.addLayout(self.custom_config_layout)
        self.login_layout.addLayout(self.btn_layout)

        self.mainLayout.addWidget(self.left_img)
        self.mainLayout.addLayout(self.login_layout)
        self.setLayout(self.mainLayout)

        self.init_custom()#读取本地用户配置

    def init_custom(self):
        custom_cfg=os.path.join(self.CONFIG_PATH,'custom.info')
        if custom_cfg:
            custom_info={}
            custom_info_str=''
            with open(custom_cfg,'r',encoding='utf8') as r:
                custom_info_str=r.read()
            if custom_info_str:
                custom_info=eval(custom_info_str)
                print(custom_info)
                try:
                    autocheck=custom_info['autocheck']
                    save_password=custom_info['save_password']
                    if autocheck:
                        self.username_eidt.setText(custom_info['user_name'])
                        self.password_edit.setText(custom_info['password'])
                        # self.auto_check.setCheckState(Qt.Checked)
                        self.user_login()
                    else:
                        if save_password:
                            self.username_eidt.setText(custom_info['user_name'])
                            self.password_edit.setText(custom_info['password'])
                            self.save_password_check.setCheckState(Qt.Checked)
                        self.show()

                        # self.close()


                except Exception as init_custom_ERR:
                    print('init_custom失败')
                    print(str(init_custom_ERR))

    def user_login(self):
        '''
        登录
        :return:
        '''
        if not os.path.exists(self.USER_INFO_PATH):
            QMessageBox.information(self, '提示', '请先注册')
        else:
            username = self.username_eidt.text()
            password = self.password_edit.text()
            showname=''
            isin=0
            with open(self.USER_INFO_PATH,'r',encoding='utf-8') as r:
                read=csv.reader(r)
                try:
                    for s in read:
                        if s[0] == username and s[1]==password:
                            isin=1
                            showname=s[2]
                            break
                        elif s[0]==username and s[1] !=password:
                            isin=2

                except:
                    pass
            if isin==1:
                # QMessageBox.information(self, '主窗口', '跳转主窗口')
                project_info_path=''
                project_info_conf = os.path.join(self.CONFIG_PATH, 'project.info')
                with open(project_info_conf, 'r', encoding='utf8') as r:
                    project_info_path = r.read()
                try:
                    self.mainwindow=MainWindow(showname,project_info_path)
                    self.mainwindow.setWindowTitle('欢迎使用BrickMover --{}'.format(showname))
                    self.mainwindow.show()
                except Exception as create_MainWindow_ERR:
                    print('打开主窗口失败')
                    print(str(create_MainWindow_ERR))
                    QMessageBox.information(self,'提示',str(create_MainWindow_ERR))

                # self.openSnipaste()
                self.close()
            elif isin==0:
                QMessageBox.information(self, '提示', '未存在该用户，请先注册')
            else:
                QMessageBox.information(self, '提示', '密码错误')


    def setting(self):
        """
        设置连接项目配置地址
        """
        project_info_conf = os.path.join(self.CONFIG_PATH, 'project.info')
        project_info_path=''
        if project_info_conf:
            with open(project_info_conf,'r',encoding='utf8') as r:
                project_info_path=r.read()
        self.projectInfoWindow=ProjectInfoWindow(project_info_path)
        self.projectInfoWindow.ip_Singnal.connect(self.set_project_info_path)
        self.projectInfoWindow.show()

    def set_project_info_path(self,path):
        if path:
            project_info_path=os.path.join(self.CONFIG_PATH,'project.info')
            with open(project_info_path,'w',encoding='utf8') as w:
                w.write(path)


    def user_setup(self):
        self.setup_window=Setup()
        self.setup_window.show()

    def _check_change(self):
        """
        更新自动登录
        :return:
        """
        auto_check=0
        save_password=0
        user_name=self.username_eidt.text()
        password=self.password_edit.text()
        if self.auto_check.isChecked():
            auto_check=1
        else:
            auto_check=0
        if self.save_password_check.isChecked():
            save_password=1
        else:
            save_password=0

        custom_info = {'autocheck':auto_check,'save_password':save_password,'user_name':user_name,'password':password}
        custom_cfg=os.path.join(self.CONFIG_PATH,'custom.info')
        if save_password or auto_check:#任何一个开启都会更新保存账号密码到本地
            if custom_cfg:
                with open(custom_cfg,'w',encoding='utf8') as w:
                    w.write(str(custom_info))



    def openSnipaste(self):
        #插件30M上下传太慢，先不用
        pass
        # os.startfile(self.SNIPASTE_PATH)

    def keyPressEvent(self, event):
        if event.key()==Qt.Key_Return:
            self.user_login()

if __name__ == '__main__':
    app=QApplication(sys.argv)
    login=Login()
    # login.show()
    sys.exit(app.exec_())

    # path='Plugins/Snipaste'
    # print(os.listdir(path))


